package com.cuitrip.business.tripservice.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.tripservice.CreateServiceSuccessActivity;
import com.cuitrip.business.tripservice.EditTripHighLightActivity;
import com.cuitrip.business.tripservice.EditTripTagsActivity;
import com.cuitrip.business.tripservice.ParaEditActivity;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.tripservice.TripDemandInstructionActivity;
import com.cuitrip.business.tripservice.TripDescriptionActivity;
import com.cuitrip.business.tripservice.TripEditActivity;
import com.cuitrip.business.tripservice.TripOtherInstructionActivity;
import com.cuitrip.business.tripservice.TripPayInstructionFragment;
import com.cuitrip.business.tripservice.model.CategoryInfo;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.tripservice.ui.TripEditView;
import com.cuitrip.business.user.ChooseCityActivity;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.choicedialog.MultiItem;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.BaseActivity;
import com.lab.mvp.presenter.Presenter;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 行程编辑页面presenter
 * Created by ak
 */
public class TripEditPresenter implements Presenter<TripEditView>, IProxyCallback{

    public static final String SERVICE_INFO_KEY = "service_info";

    public static final int PREVIEW_ACTION = 0x01;
    public static final int DRAFT_ACTION = 0x02;
    public static final int COMMIT_ACTION = 0x03;
    public static final int TITLE_TYPE = 0x01;
    public static final int LOCATION_TYPE = 0x02;
    public static final int HIGHLIGHT_TYPE = 0x03;
    public static final int DESCRIPTION_TYPE = 0x04;
    public static final int OTHER_INSTRUCTION_TYPE = 0x05;
    public static final int DEMAND_INSTRUCTION_TYPE = 0x06;
    public static final int PAY_INSTRUCTION_TYPE = 0x07;


    TripEditView mTripEditView;

    private ServiceInfo mServiceInfo;

    private int mSaveAction;

    private ApiProxy mApiProxy = new ApiProxy(this);

    @Override
    public void attachView(TripEditView view) {
        mTripEditView = view;
    }

    public ServiceInfo initServiceInfo(ServiceInfo serviceInfo, TripEditActivity.ContentMode contentMode){
        mServiceInfo = serviceInfo;
        if (mServiceInfo == null){
            mServiceInfo = new ServiceInfo();
        }
        mServiceInfo.setEditMode(contentMode);
        return mServiceInfo;
    }

    public void renderUi(){
        mTripEditView.renderTitle(mServiceInfo);
        mTripEditView.renderLocation(mServiceInfo);
        renderHighLight();
        mTripEditView.renderDescription(mServiceInfo);
        mTripEditView.renderOtherNotes(mServiceInfo);
        mTripEditView.renderDemands(mServiceInfo);
        renderPayInstruction();
    }

    public void navigateToSelectCity(BaseActivity activity, Fragment fragment){
        Intent intent = new Intent(activity,ChooseCityActivity.class);
        intent.putExtra(ChooseCityActivity.KEY_SAVE_CITY,false);
        intent.putExtra(ChooseCityActivity.KEY_LIST_TYPE,ServiceBusiness.SERVICE_TYPE);
        fragment.startActivityForResult(intent,ChooseCityActivity.REQUEST_CODE_CHOOSE_CITY);
    }

    public void navigateToHighLight(BaseActivity activity, Fragment fragment){
        Intent intent = new Intent(activity, EditTripHighLightActivity.class);
        intent.putExtra(ParaEditActivity.TITLE_KEY, ResourceUtil.getString(R.string.trip_attribute_highlight));
        intent.putExtra(SERVICE_INFO_KEY, mServiceInfo);
        if (!TextUtils.isEmpty(mServiceInfo.getHighLight())) {
            intent.putExtra(ParaEditActivity.PARA_KEY, ParaProxy.getInstance().getParaList(mServiceInfo.getHighLight()));
        }
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/highlights");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/highlights");
        }
        fragment.startActivityForResult(intent, HIGHLIGHT_TYPE);
    }

    public void navigateToDescription(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/description");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/description");
        }
        Intent intent = new Intent(activity, TripDescriptionActivity.class);
        if (!TextUtils.isEmpty(mServiceInfo.getServiceDescript())) {
            intent.putExtra(TripEditActivity.SERVICE_INFO_KEY, mServiceInfo)
                    .putExtra(TripDescriptionActivity.EDIT_MODE, true);
        }
        fragment.startActivityForResult(intent, DESCRIPTION_TYPE);
    }

    public void navigateOtherInstruction(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/additional");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/additional");
        }
        mServiceInfo.otherNotes.setContentMode(mServiceInfo.getEditMode());
        Intent intent = TripOtherInstructionActivity.getOtherNotesIntent(activity, mServiceInfo.getOtherNotes(),true);
        fragment.startActivityForResult(intent, OTHER_INSTRUCTION_TYPE);
    }

    public void navigate2Demand(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/booking");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/booking");
        }

        Intent intent = new Intent(activity, TripDemandInstructionActivity.class);
        intent.putExtra(SERVICE_INFO_KEY, mServiceInfo);
        fragment.startActivityForResult(intent, DEMAND_INSTRUCTION_TYPE);
    }



    public void navigateToPayInstruction(BaseActivity activity){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/price");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/price");
        }
        TripPayInstructionFragment tripPayInstructionFragment = new TripPayInstructionFragment();
        tripPayInstructionFragment.setTripMainUpdater(this);
        Bundle bundle = new Bundle();
        bundle.putSerializable(TripEditActivity.SERVICE_INFO_KEY, mServiceInfo);
        tripPayInstructionFragment.setArguments(bundle);
        activity.openFragment(tripPayInstructionFragment, R.id.container, TripPayInstructionFragment.class.getName(), true);
    }

    public void commitTrip(String title){
        mServiceInfo.setName(title);
        ServiceFormProxy.InValidType inValidType = ServiceFormProxy.getInstance().isFormComplete(mServiceInfo);
        boolean isValid = mTripEditView.performInvalidAction(inValidType);
        if (!isValid) {
            return;
        }
        mTripEditView.showLoadingDialog();
        mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
        mSaveAction = COMMIT_ACTION;
        ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
    }

    public void preview(String title) {
        mServiceInfo.setName(title);
        ServiceFormProxy.InValidType inValidType = ServiceFormProxy.getInstance().isFormComplete(mServiceInfo);
        boolean isValid = mTripEditView.performInvalidAction(inValidType);
        if (!isValid) {
            return;
        }
        mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
        mSaveAction = PREVIEW_ACTION;
        ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
    }

    public void onLeftPage(final String title){
        String[] tip;
        if (mServiceInfo.isUnSync()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isChecked()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isCheckFailed()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isDraft()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isChecking()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else {
            return;
        }

        final ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
        List<MultiItem> multiItemList = new ArrayList<MultiItem>();
        for (String apiString : tip) {
            MultiItem multiItem = new MultiItem(apiString);
            if (apiString.equals(ResourceUtil.getString(R.string.operation_save_as_draft))){
                multiItem.setColor(ResourceUtil.getThemeColor());
            }else{
                multiItem.setColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
            }
            multiItemList.add(multiItem);
        }
        choiceDialog.setDialogMessageVisibility(false);
        choiceDialog.setDialogTitleVisibility(false);
        choiceDialog.setDialogMultiStyleSetting(multiItemList, new ChoiceDialog.DialogStyleMultiCallback() {
            @Override
            public boolean onMultiItemClick(MultiItem multiItem, int position) {
                if (position == 0) {
                    if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft()|| mServiceInfo.isChecking()) {
                        mServiceInfo.setName(title);
                        if (TextUtils.isEmpty(mServiceInfo.getName())) {
                            mTripEditView.performInvalidAction(ServiceFormProxy.InValidType.TITLE);
                        } else {
                            mTripEditView.showLoadingDialog();
                            mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
                            mSaveAction = DRAFT_ACTION;
                            ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);

                        }
                    } else {
                        mTripEditView.finishPage();
                    }
                } else if (position == 1) {
                    if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft()||mServiceInfo.isChecking()) {
                        mTripEditView.finishPage();
                    }

                }
                choiceDialog.dismiss();
                return true;
            }
        });
        mTripEditView.showDialogFragment(choiceDialog);
    }


    public boolean handleActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode==ChooseCityActivity.REQUEST_CODE_CHOOSE_CITY) {
            if (resultCode== Activity.RESULT_OK){
                String provinceAbbr = data.getStringExtra(ChooseCityActivity.KEY_PROVINCE_ABBR);
                String cityAbbr = data.getStringExtra(ChooseCityActivity.ABBR_KEY);
                String city=data.getStringExtra(ChooseCityActivity.CITY_KEY);
                mServiceInfo.setAddress(city);
                mServiceInfo.setCountry(provinceAbbr);
                mServiceInfo.setCity(cityAbbr);
                mServiceInfo.setCityAbbr(cityAbbr);
                mTripEditView.renderLocation(mServiceInfo);
                return true;
            }
        }else if (requestCode == HIGHLIGHT_TYPE) {
            if (resultCode == Activity.RESULT_OK) {
                List<CharSequence> highList = data.getCharSequenceArrayListExtra(ParaEditActivity.PARA_KEY);
                List<CategoryInfo> categoryInfoList = data.getParcelableArrayListExtra(EditTripTagsActivity.TAG_KEY);
                mServiceInfo.setHighLight(ParaProxy.getInstance().outputPara(highList));
                mServiceInfo.setCateList(categoryInfoList);
                renderHighLight();
                return true;
            }
        }else if (requestCode == DESCRIPTION_TYPE) {
            if (resultCode == Activity.RESULT_OK){
                mServiceInfo.setBackPic(data.getStringExtra(TripDescriptionActivity.BACK_PIC_KEY));
                mServiceInfo.setPic(data.getStringArrayListExtra(TripDescriptionActivity.PIC_LIST_KEY));
                mServiceInfo.setServiceDescript(data.getStringExtra(TripDescriptionActivity.DESC_KEY));
                mTripEditView.renderDescription(mServiceInfo);
                return true;
            }
        }else if (requestCode == OTHER_INSTRUCTION_TYPE) {
            if (resultCode == Activity.RESULT_OK) {
                //java 的数据结构，咳咳，看看有没有更好的方式
                List<CharSequence> safeTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.SAFE_KEY);
                mServiceInfo.otherNotes.setServiceSafeTips(ParaProxy.getInstance().outputPara(safeTips));

                List<CharSequence> attentionTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.ATTENTION_KEY);
                mServiceInfo.otherNotes.setServiceNotice(ParaProxy.getInstance().outputPara(attentionTips));

                List<CharSequence> clothTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.CLOTH_KEY);
                mServiceInfo.otherNotes.setServiceWearTips(ParaProxy.getInstance().outputPara(clothTips));

                List<CharSequence> weatherTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.WEATHER_KEY);
                mServiceInfo.otherNotes.setUnexpectedWeather(ParaProxy.getInstance().outputPara(weatherTips));
                mTripEditView.renderOtherNotes(mServiceInfo);
            }
        } else if (requestCode == DEMAND_INSTRUCTION_TYPE) {
            mServiceInfo.setMeetingPlace(data.getStringExtra(TripDemandInstructionActivity.MEETINGPLACE_KEY));
            mServiceInfo.setLat(data.getStringExtra(TripDemandInstructionActivity.LATITUDE_KEY));
            mServiceInfo.setLng(data.getStringExtra(TripDemandInstructionActivity.LONGTITUDE_KEY));
            mServiceInfo.setServiceTime(data.getStringExtra(TripDemandInstructionActivity.DURATION_KEY));
            mServiceInfo.setBestTime(data.getStringExtra(TripDemandInstructionActivity.BESTTIME_KEY));
            mServiceInfo.setMinBuyerNum(data.getIntExtra(TripDemandInstructionActivity.PERSON_MIN_KEY, 0));
            mServiceInfo.setMaxbuyerNum(data.getIntExtra(TripDemandInstructionActivity.PERSON_MAX_KEY, 0));
            mServiceInfo.setPreOrderDays(data.getIntExtra(TripDemandInstructionActivity.ADVANCE_DAY_KEY, 1));
            mTripEditView.renderDemands(mServiceInfo);
        }
        return false;
    }


    public void renderPayInstruction(){
        mTripEditView.renderPayInfo(mServiceInfo);
    }

    public void renderHighLight(){
        mTripEditView.renderHighLight(mServiceInfo);
    }


    @Override
    public void detachView() {
        this.mTripEditView = null;
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        mTripEditView.hideLoadingDialog();
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response!= null && response.code == CtResponseCode.RESULT_OK){
            if (response.result instanceof ServiceInfo) {
                ServiceInfo serviceInfo= (ServiceInfo) response.result;
                mServiceInfo.setSid(serviceInfo.getSid());
                handleSuccessResult(serviceInfo);
            }
        }else{
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }

    private void handleSuccessResult(ServiceInfo serviceInfo){
        Context context = mTripEditView.getContext();
        if (context == null){
            return;
        }
        LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(
                new Intent(TripServiceListFragment.TRIP_SERVICE_STATUS_CHANGED));
        if (mSaveAction == COMMIT_ACTION){
            context.startActivity(new Intent(context, CreateServiceSuccessActivity.class));
            mTripEditView.finishPage();
        }else if (mSaveAction == DRAFT_ACTION){
            mTripEditView.finishPage();
        }else if (mSaveAction == PREVIEW_ACTION){
            TrackUtil.trackScreenName("/insider/trips/preview");
            ServiceDetailActivity.startFinder(context, serviceInfo.getSid(), ServiceInfo.STATUS_DRAFT);
        }

    }


}
